package com.fy.utils;

import lombok.extern.slf4j.Slf4j;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.rendering.PDFRenderer;
import org.apache.poi.hslf.usermodel.HSLFSlide;
import org.apache.poi.hslf.usermodel.HSLFSlideShow;
import org.apache.poi.hslf.usermodel.HSLFTextParagraph;
import org.apache.poi.hslf.usermodel.HSLFTextRun;
import org.apache.poi.hssf.converter.ExcelToHtmlConverter;
import org.apache.poi.hssf.usermodel.HSSFPictureData;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.hwpf.HWPFDocument;
import org.apache.poi.hwpf.converter.PicturesManager;
import org.apache.poi.hwpf.converter.WordToHtmlConverter;
import org.apache.poi.hwpf.usermodel.PictureType;
import org.apache.poi.xslf.usermodel.*;
import org.apache.poi.xwpf.converter.core.FileURIResolver;
import org.apache.poi.xwpf.converter.xhtml.XHTMLConverter;
import org.apache.poi.xwpf.converter.xhtml.XHTMLOptions;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.poi.xwpf.usermodel.XWPFPictureData;
import org.fit.pdfdom.PDFDomTree;
import org.springframework.util.ClassUtils;
import org.w3c.dom.Document;

import javax.imageio.ImageIO;
import javax.imageio.stream.FileImageOutputStream;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import java.awt.*;
import java.awt.geom.Rectangle2D;
import java.awt.image.BufferedImage;
import java.io.*;
import java.util.ArrayList;
import java.util.List;

/**
 * word 转换成html
 */
@Slf4j
public class DocToHtmlUtil {

    /**
     * 2007版本word转换成html docx
     */
    public static void wordDocxToHtml(File file, String filePath, String htmlPath) throws IOException {
        String imagepath = htmlPath.substring(0,htmlPath.lastIndexOf("/") + 1);//解析时候如果doc文件中有图片  图片会保存在此路径
        String fileName = filePath.substring(filePath.lastIndexOf("/") + 1,filePath.lastIndexOf("."));
        File f = file==null?new File(filePath):file;
        if (!f.exists()) {
            System.out.println("Sorry File does not Exists!");
        } else {
            if (filePath.indexOf(".DOCX") > -1 || filePath.indexOf(".docx") > -1) {

                // 加载word文档生成 XWPFDocument对象
                InputStream in = new FileInputStream(f);
                XWPFDocument document = new XWPFDocument(in);

                // 解析 XHTML配置 (这里设置IURIResolver来设置图片存放的目录)
                File imageFolderFile = new File(imagepath);
                XHTMLOptions options = XHTMLOptions.create().URIResolver(new FileURIResolver(imageFolderFile));
                //options.setExtractor(new FileImageExtractor(imageFolderFile));
                options.setIgnoreStylesIfUnused(false);
                options.setFragment(true);


                //写入图片
                List<XWPFPictureData> piclist = document.getAllPictures();
                for (int i = 0; i <piclist.size() ; i++) {
                    XWPFPictureData pic = piclist.get(i);
                    OutputStream outp = new FileOutputStream(imagepath + fileName +"-" + pic.getFileName());
                    outp.write(pic.getData());
                    outp.close();
                }

                // 将 XWPFDocument转换成XHTML
                Writer sw = new StringWriter();
                XHTMLConverter converter = new XHTMLConverter();
                converter.convert(document, sw, options);
                String content = sw.toString();
                System.out.println(imagepath);
                content = content.replaceAll(imagepath , "");
                content =  content.replaceAll("word/media/", fileName +"-");
                OutputStream out = new FileOutputStream(new File(htmlPath));
                out.write(content.getBytes());
                out.close();
            } else {
                System.out.println("Enter only MS Office 2007+ files");
            }
        }
    }

    /**
     * /**
     * 2003版本word转换成html
     * @throws IOException
     * @throws TransformerException
     * @throws ParserConfigurationException
     */
    public static void wordDocToHtml(File file, String filePath, String htmlPath) throws IOException, TransformerException, ParserConfigurationException {
        String imagepath = htmlPath.substring(0,htmlPath.lastIndexOf("/") + 1);//解析时候如果doc文件中有图片  图片会保存在此路径
        String fileName = filePath.substring(filePath.lastIndexOf("/") + 1,filePath.lastIndexOf("."));
        InputStream input = new FileInputStream(file==null?new File(filePath):file);
        HWPFDocument wordDocument = new HWPFDocument(input);
        WordToHtmlConverter wordToHtmlConverter = new WordToHtmlConverter(DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument());
        //设置图片存放的位置
        wordToHtmlConverter.setPicturesManager(new PicturesManager() {
            public String savePicture(byte[] content, PictureType pictureType, String suggestedName, float widthInches, float heightInches) {
                File imgPath = new File(imagepath);
                if(!imgPath.exists()){//图片目录不存在则创建
                    imgPath.mkdirs();
                }
                File file = new File(imagepath + fileName +"-"+ suggestedName);
                try {
                    OutputStream os = new FileOutputStream(file);
                    os.write(content);
                    os.close();
                } catch (FileNotFoundException e) {
                   e.printStackTrace();

                } catch (IOException e) {
                   e.printStackTrace();

                }
                return imagepath + suggestedName;
            }
        });

        //解析word文档
        wordToHtmlConverter.processDocument(wordDocument);
        Document htmlDocument = wordToHtmlConverter.getDocument();

        File htmlFile = new File(htmlPath);
        OutputStream outStream = new FileOutputStream(htmlFile);

        //也可以使用字符数组流获取解析的内容
//        ByteArrayOutputStream baos = new ByteArrayOutputStream();
//        OutputStream outStream = new BufferedOutputStream(baos);

        Writer sw = new StringWriter();
        DOMSource domSource = new DOMSource(htmlDocument);
        StreamResult streamResult = new StreamResult(sw);

        TransformerFactory factory = TransformerFactory.newInstance();
        Transformer serializer = factory.newTransformer();
        serializer.setOutputProperty(OutputKeys.ENCODING, "utf-8");
        serializer.setOutputProperty(OutputKeys.INDENT, "yes");
        serializer.setOutputProperty(OutputKeys.METHOD, "html");
        serializer.transform(domSource, streamResult);

        String content = sw.toString();
        content =  content.replaceAll(imagepath, fileName +"-");
        outStream.write(content.getBytes());
        //也可以使用字符数组流获取解析的内容
//        String content = baos.toString();
//        System.out.println(content);
//        baos.close();
        outStream.close();
    }

    public static void excelToHtml(File file, String filePath, String htmlPath) throws Exception {
        final String imagepath = htmlPath.substring(0,htmlPath.lastIndexOf("/") + 1);//解析时候如果doc文件中有图片  图片会保存在此路径
        String fileName = filePath.substring(filePath.lastIndexOf("/") + 1,filePath.lastIndexOf("."));
        InputStream input=new FileInputStream(file==null?new File(filePath):file);
        HSSFWorkbook excelBook=new HSSFWorkbook(input);


        String sheetName = "C-S-R";
        for (int i = 0; i < excelBook.getNumberOfSheets() ; i++) {
            excelBook.setSheetHidden(i,true);
            sheetName = "C-S-R" + i;
            excelBook.setSheetName(i, sheetName);
        }


        ExcelToHtmlConverter excelToHtmlConverter = new ExcelToHtmlConverter (DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument() );
        excelToHtmlConverter.processWorkbook(excelBook);

        List<HSSFPictureData> pics = excelBook.getAllPictures();
        if (pics != null) {
            for (int i = 0; i < pics.size(); i++) {
                File fileimg = new File(imagepath + fileName +"-"+ i +".jpg" );
                try {
                    OutputStream os = new FileOutputStream(fileimg);
                    os.write(pics.get(i).getData());
                    os.close();
                } catch (FileNotFoundException e) {
                   e.printStackTrace();

                } catch (IOException e) {
                   e.printStackTrace();

                }
            }
        }
        File htmlFile = new File(htmlPath);
        Writer sw = new StringWriter();
        Document htmlDocument =excelToHtmlConverter.getDocument();
        OutputStream outStream = new FileOutputStream(htmlFile);
        DOMSource domSource = new DOMSource (htmlDocument);
        StreamResult streamResult = new StreamResult (sw);
        TransformerFactory tf = TransformerFactory.newInstance();
        Transformer serializer = tf.newTransformer();
        serializer.setOutputProperty (OutputKeys.ENCODING, "utf-8");
        serializer.setOutputProperty (OutputKeys.INDENT, "yes");
        serializer.setOutputProperty (OutputKeys.METHOD, "html");
        serializer.transform (domSource, streamResult);
        String content = sw.toString();
        //替换所有的sheetName
        content =  content.replaceAll("(?:C-S-R)\\d+", "");


        String html = " <script>\n" +
                "                var tagName = document.getElementsByTagName('th');\n" +
                "        for (var i =0; i < tagName.length; i++){\n" +
                "            tagName[i].innerHTML = '';\n" +
                "        }\n" +
                "</script>";

        //替换所有<th>标签
        content =  content.replaceAll("</body>",html + "</body>");

        //替换所有的图片地址
        content =  content.replaceAll(imagepath, fileName +"-");
        outStream.write(content.getBytes());

        outStream.close();
    }
    /*
      pdf转换html
       */
    public static void pdfToHtml(File file, String filePath,String htmlPath)  {
        try{
            BufferedWriter out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(htmlPath),"utf-8"));
            //加载PDF文档
            //PDDocument document = PDDocument.load(bytes);
            PDDocument document = PDDocument.load(file==null?new File(filePath):file);
            PDFDomTree pdfDomTree = new PDFDomTree();
            pdfDomTree.writeText(document,out);
        } catch (Exception e) {
           e.printStackTrace();

        }
    }

    public static void PdfToImage(String pdfurl){
            StringBuffer buffer = new StringBuffer();
            FileOutputStream fos;
            PDDocument document;
            File pdfFile;
            int size;
            BufferedImage image;
            FileOutputStream out;
            Long randStr = 0l;
            //PDF转换成HTML保存的文件夹
            String path = "D:\\temp\\image\\";
            File htmlsDir = new File(path);
            if(!htmlsDir.exists()){
                htmlsDir.mkdirs();
            }
            File htmlDir = new File(path+"/");
            if(!htmlDir.exists()){
                htmlDir.mkdirs();
            }
            try{
                //遍历处理pdf附件
                randStr = System.currentTimeMillis();
                buffer.append("<!doctype html>\r\n");
                buffer.append("<head>\r\n");
                buffer.append("<meta charset=\"UTF-8\">\r\n");
                buffer.append("</head>\r\n");
                buffer.append("<body style=\"background-color:gray;\">\r\n");
                buffer.append("<style>\r\n");
                buffer.append("img {background-color:#fff; text-align:center; width:100%; max-width:100%;margin-top:6px;}\r\n");
                buffer.append("</style>\r\n");
                document = new PDDocument();
                //pdf附件
                pdfFile = new File(pdfurl);
                document = PDDocument.load(pdfFile, (String) null);
                size = document.getNumberOfPages();
                Long start = System.currentTimeMillis(), end = null;
                System.out.println("===>pdf : " + pdfFile.getName() +" , size : " + size);
                PDFRenderer reader = new PDFRenderer(document);
                for(int i=0 ; i < size; i++){
                    //image = new PDFRenderer(document).renderImageWithDPI(i,130,ImageType.RGB);
                    image = reader.renderImage(i, 1.5f);
                    //生成图片,保存位置
                    out = new FileOutputStream(path + "/"+ "image" + "_" + i + ".jpg");
                    ImageIO.write(image, "png", out); //使用png的清晰度
                    //将图片路径追加到网页文件里
                    buffer.append("<img src=\"" + path +"/"+ "image" + "_" + i + ".jpg\"/>\r\n");
                    image = null; out.flush();
                    out.close();
                }
                reader = null;
                document.close();
                buffer.append("</body>\r\n");
                buffer.append("</html>");
                end = System.currentTimeMillis() - start;
                System.out.println("===> Reading pdf times: " + (end/1000));
                start = end = null;
                //生成网页文件
                fos = new FileOutputStream(path+randStr+".html");
                System.out.println(path+randStr+".html");
                fos.write(buffer.toString().getBytes());
                fos.flush(); fos.close();
                buffer.setLength(0);

            }catch(Exception e){
                System.out.println("===>Reader parse pdf to jpg error : " + e.getMessage());
                e.printStackTrace();
            }
        }



    /*
     * txt文档转html
       filePath:txt原文件路径
       htmlPosition:转化后生成的html路径
    */
    public static void txtToHtml(File file, String filePath, String htmlPath) {
        try {
            //String encoding = "GBK";
            file = file==null?new File(filePath):file;
            if (file.isFile() && file.exists()) { // 判断文件是否存在
                InputStreamReader read = new InputStreamReader(new FileInputStream(file), "UTF-8");
                // 考虑到编码格式
                BufferedReader bufferedReader = new BufferedReader(read);
                // 写文件
                FileOutputStream fos = new FileOutputStream(new File(htmlPath));
                OutputStreamWriter osw = new OutputStreamWriter(fos, "GBK");
                BufferedWriter bw = new BufferedWriter(osw);
                String lineTxt = null;
                while ((lineTxt = bufferedReader.readLine()) != null) {
                    bw.write("&nbsp&nbsp&nbsp"+lineTxt + "</br>");
                }
                bw.close();
                osw.close();
                fos.close();
                read.close();
            } else {
                System.out.println("找不到指定的文件");
            }
        } catch (Exception e) {
            System.out.println("读取文件内容出错");
           e.printStackTrace();

        }
    }

    public static void pptxToHtml(File file, String filePath, String htmlPath) throws Exception{
        final String imagepath = htmlPath.substring(0,htmlPath.lastIndexOf("/") + 1);//解析时候如果doc文件中有图片  图片会保存在此路径
        String fileName = filePath.substring(filePath.lastIndexOf("/") + 1,filePath.lastIndexOf("."));
        List<String> imgNamesList=new ArrayList<String>();//PPT转成图片后所有名称集合
        try {
            FileInputStream inputStream = new FileInputStream(file==null?new File(filePath):file);
            XMLSlideShow xmlSlideShow = new XMLSlideShow(inputStream);
            List<XSLFSlide> xslfSlides = xmlSlideShow.getSlides();
            //PPT每页的大小（宽和高度）
            Dimension  onePPTPageSize= xmlSlideShow.getPageSize();

            //inputStream.close();
            for (int i = 0; i < xslfSlides.size(); i++) {
                for (XSLFShape shape : xslfSlides.get(i).getShapes()) {
                    if (shape instanceof XSLFTextShape) {
                        XSLFTextShape txtshape = (XSLFTextShape)shape ;
                        for (XSLFTextParagraph paragraph : txtshape.getTextParagraphs()) {
                            List<XSLFTextRun> truns = paragraph.getTextRuns();
                            for (XSLFTextRun trun : truns) {

                                Double size= trun.getFontSize();
                                //判断获取的文本是不是为空  这一步很重要不然会包错
                                if(trun.getRawText() == null){
                                    trun.setText("");
                                }
                                if((size<=0)||(size>=26040)){
                                    trun.setFontSize(7.0);
                                }
                                trun.setFontFamily("宋体");
                            }
                        }
                    }

                }
                /**
                 * 创建BufferedImage对象，图像的尺寸为原来的每页的尺寸
                 */
                BufferedImage oneBufferedImage=new BufferedImage(onePPTPageSize.width, onePPTPageSize.height, BufferedImage.TYPE_INT_RGB);
                Graphics2D oneGraphics2D=oneBufferedImage.createGraphics();
                /**
                 * 设置转换后的图片背景色为白色
                 *
                 */
                oneGraphics2D.setPaint(Color.white);
                oneGraphics2D.fill(new Rectangle2D.Float(0,0,onePPTPageSize.width,onePPTPageSize.height));
                xslfSlides.get(i).draw(oneGraphics2D);

                /**
                 * 设置图片的存放路径和图片格式，注意生成的图片路径为绝对路径，最终获得各个图像文件所对应的输出流对象
                 */
                String imgName= fileName +"-"+ (i+1)+"."+"jpg";
                imgNamesList.add(imgName);//将图片名称添加的集合中


                //OutputStreamWriter oStreamWriter = new OutputStreamWriter(new FileOutputStream(imagepath+imgName), "utf-8");

                FileOutputStream outputStream = new FileOutputStream(imagepath+imgName);
                //写入图片
                ImageIO.write(oneBufferedImage,"jpg",outputStream);


                outputStream.close();

            }

            String imgStr = "";
            for (int i = 0; i <imgNamesList.size() ; i++) {
                imgStr += "<div><img src=\""+imgNamesList.get(i)+"\"></div>";
            }
            FileOutputStream outhtml = new FileOutputStream(htmlPath);

            String content="<html><head><META http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\"></head><body>"+imgStr+"</body></html>";
            outhtml.write(content.getBytes());
            outhtml.close();
        } catch (Exception e) {
           e.printStackTrace();

        }
    }

    public static void pptToHtml(File file, String filePath, String htmlPath) throws Exception {
        final String imagepath = htmlPath.substring(0,htmlPath.lastIndexOf("/") + 1);//解析时候如果doc文件中有图片  图片会保存在此路径
        String fileName = filePath.substring(filePath.lastIndexOf("/") + 1,filePath.lastIndexOf("."));
        List<String> imgNamesList=new ArrayList<String>();//PPT转成图片后所有名称集合

        FileInputStream inputStream = new FileInputStream(file==null?new File(filePath):file);
        FileOutputStream outputStream = null;
        HSLFSlideShow hslfSlideShow =new HSLFSlideShow(inputStream);


        try{
            //PPT每页的大小（宽和高度）
            Dimension  onePPTPageSize= hslfSlideShow.getPageSize();
            //获得PPT文件中的所有的PPT页面（获得每一张幻灯片）,并转为一张张的播放片
            List<HSLFSlide> pptPageSlideList=hslfSlideShow.getSlides();
            //下面循环的主要功能是实现对PPT文件中的每一张幻灯片进行转换和操作
            for (int i = 0; i <pptPageSlideList.size(); i++) {
                //这几个循环只要是设置字体为宋体，防止中文乱码，
                List<List<HSLFTextParagraph>>  oneTextParagraphs=pptPageSlideList.get(i).getTextParagraphs();
                for (List<HSLFTextParagraph> list :oneTextParagraphs) {
                    for (HSLFTextParagraph hslfTextParagraph : list) {
                        List<HSLFTextRun> HSLFTextRunList= hslfTextParagraph.getTextRuns();
                        for (int j = 0; j <HSLFTextRunList.size(); j++) {
                            /*
                             * 如果PPT在WPS中保存过，则 HSLFTextRunList.get(j).getFontSize();的值为0或者26040，
                             * 因此首先识别当前文本框内的字体尺寸是否为0或者大于26040，则设置默认的字体尺寸。
                             */
                            //设置字体大小
                            Double size= HSLFTextRunList.get(j).getFontSize();
                            if((size<=0)||(size>=26040)){
                                HSLFTextRunList.get(j).setFontSize(7.0);
                            }
                            //设置字体样式为宋体
                            //String family=HSLFTextRunList.get(j).getFontFamily();
                            HSLFTextRunList.get(j).setFontFamily("宋体");
                        }
                    }

                }
                /**
                 * 创建BufferedImage对象，图像的尺寸为原来的每页的尺寸
                 */
                BufferedImage oneBufferedImage=new BufferedImage(onePPTPageSize.width, onePPTPageSize.height, BufferedImage.TYPE_INT_RGB);
                Graphics2D oneGraphics2D=oneBufferedImage.createGraphics();
                /**
                 * 设置转换后的图片背景色为白色
                 *
                 */
                oneGraphics2D.setPaint(Color.white);
                oneGraphics2D.fill(new Rectangle2D.Float(0,0,onePPTPageSize.width,onePPTPageSize.height));
                pptPageSlideList.get(i).draw(oneGraphics2D);
                /**
                 * 设置图片的存放路径和图片格式，注意生成的图片路径为绝对路径，最终获得各个图像文件所对应的输出流对象
                 */
                String imgName= fileName +"-"+ (i+1)+"."+"jpg";
                imgNamesList.add(imgName);//将图片名称添加的集合中


                //OutputStreamWriter oStreamWriter = new OutputStreamWriter(new FileOutputStream(imagepath+imgName), "utf-8");

                outputStream = new FileOutputStream(imagepath+imgName);
                //写入图片
                ImageIO.write(oneBufferedImage,"jpg",outputStream);
            }


            String imgStr = "";
            for (int i = 0; i <imgNamesList.size() ; i++) {
                imgStr += "<div><img src=\""+imgNamesList.get(i)+"\"></div>";
            }
            FileOutputStream outhtml = new FileOutputStream(htmlPath);

            String content="<html><head><META http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\"></head><body>"+imgStr+"</body></html>";
            outhtml.write(content.getBytes());
            outhtml.close();
        }finally{
            outputStream.close();
        }
    }

    public static String fileIsToHtml(String filePath, File file,String htmlPath) throws Exception {
        String sux = filePath.substring(filePath.lastIndexOf(".") + 1, filePath.length()).toUpperCase();
        String fileSux = "PDF,DOC,TXT,DOCX,PPT,XLS,XLSX,PPTX";
        //需要转HTML的
        if(fileSux.indexOf(sux) > -1){
            if(htmlPath == null){
                htmlPath = filePath + ".html";
            }else{
                File desc = new File(htmlPath);
                if (!desc.getParentFile().exists()) {
                    desc.getParentFile().mkdirs();
                }
                if (!desc.exists()) {
                    desc.createNewFile();
                }
            }
            switch (sux){
                case "DOC":
                    wordDocToHtml(file,filePath, htmlPath);
                    break;
                case "DOCX":
                    wordDocxToHtml(file,filePath, htmlPath);
                    break;
                case "PDF":
                    pdfToHtml(file,filePath, htmlPath);
                    break;
                case "TXT":
                    txtToHtml(file,filePath, htmlPath);
                    break;
                case "PPT":
                    pptToHtml(file,filePath, htmlPath);
                    break;
                case "PPTX":
                    pptxToHtml(file,filePath, htmlPath);
                    break;
                case "XLS":
                    excelToHtml(file,filePath, htmlPath);
                    break;
                case "XLSX":
                    //ExcelConvertHTMLUtils.excelConvertHTMLHandle(file,filePath, htmlPath);
                    break;
                default:
                    break;
            }
            return htmlPath;
        }
        return null;
    }

    public static String imageCodeing(String filePath, File file, String htmlPath) throws IOException {
        String sux = filePath.substring(filePath.lastIndexOf(".") + 1, filePath.length()).toUpperCase();
        String imgSux = "JPG,JPEG,PNG,GIF,BMP,SVG,WMF,WEBP";
        if(imgSux.indexOf(sux) > -1){
            htmlPath = htmlPath.substring(0,htmlPath.lastIndexOf(".")) + "-s" + "." + sux;
            File desc = new File(htmlPath);
            if (!desc.getParentFile().exists()) {
                desc.getParentFile().mkdirs();
            }
            if (!desc.exists()) {
                desc.createNewFile();
            }

            generateImage(file,htmlPath);
            return htmlPath;
        }
        return null;
    }


    public static void generateImage(File file,String htmlPath) {
        try {
            //logo
            BufferedImage watermarkImage = ImageIO.read(new File(ClassUtils.getDefaultClassLoader().getResource("").getPath() + "static/img/logo-yj.png"));
            //图片
            BufferedImage bgImage = ImageIO.read(file);
            int bgWidth = bgImage.getWidth(null);
            int bgHeight = bgImage.getHeight(null);
            BufferedImage image = new BufferedImage(bgWidth, bgHeight, BufferedImage.TYPE_INT_RGB);
            Graphics2D g = image.createGraphics();
            g.drawImage(bgImage, 0, 0, bgWidth, bgHeight, null);
            int width = watermarkImage.getWidth();
            int height = watermarkImage.getHeight();
            //水印夹在左下角
            g.drawImage(watermarkImage, (bgWidth-width-5), (bgHeight-height-5), width, height, null);
            g.dispose();
            ByteArrayOutputStream out = new ByteArrayOutputStream();
            ImageIO.write(image, "jpg", out);
            byte[] bytes = out.toByteArray();
            FileImageOutputStream imageOutput = new FileImageOutputStream(new File(htmlPath));
            imageOutput.write(bytes, 0, bytes.length);
            imageOutput.close();
        } catch (Exception e) {
           e.printStackTrace();

        }
    }

    public static void main(String[] args) throws Exception {
        //wordDocToHtml(new File("D:/kpgx/download/有图片的.doc"),"download/有图片的.doc","D:/kpgx/download/2020/1.html");
        //wordDocxToHtml(new File("D:/kpgx/download/应急管理科普知识宣传-应急科普知识.docx"),"应急管理科普知识宣传-应急科普知识.docx","D:/kpgx/download/2020/2.html");
       //excelToHtml(new File("D:/kpgx/download/应急预案演练方案(记录表).xls"),"download/应急预案演练方案(记录表).xls","D:/kpgx/download/2020/3.html");
        //ExcelConvertHTMLUtils.excelConvertHTMLHandle(new File("D:/kpgx/download/应急预案演练方案(记录表).xlsx"),"download/应急预案演练方案(记录表).xlsx","D:/kpgx/download/2020/4.html");
        pdfToHtml(new File("D:\\temp\\2021\\3\\26\\9c903833-966e-4540-a600-3a7f6b1a97a6.PDF"),"2021\\3\\26\\9c903833-966e-4540-a600-3a7f6b1a97a6.PDF", "D:\\temp\\2021\\3\\26\\6.html");
        //txtToHtml(new File("D:/kpgx/download/测试.txt"),"download/测试.txt", "D:/kpgx/download/2020/7.html");
        //pptxToHtml(new File("D:/kpgx/download/1.pptx"),"download/1.pptx","D:/kpgx/download/2020/8.html");
        //pptToHtml(new File("D:/kpgx/download/防震减灾科普知识-(中小学(课堂PPT).ppt"),"download/防震减灾科普知识-(中小学(课堂PPT).ppt","D:/kpgx/download/2020/9.html");


        //imageCodeing("D:\\娱乐\\电脑图片\\image\\4adae351f665fc07437471dcf73e332d.jpg",new File("D:\\娱乐\\电脑图片\\image\\微信图片_20181117225949.jpg"),"D:\\娱乐\\电脑图片\\image\\4adae351f665fc07437471dcf73e332d.jpg.html");

        //fileIsToHtml("D:/kpgx/download/2020/2.docx",new File("D:/kpgx/download/应急管理科普知识宣传-应急科普知识.docx"),"D:/kpgx/download/2020/2.docx.html");
    }


}